﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration.Provider;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
//using System.Web.Security;
using T2.WebSecurity.Business.Entities;
using T2.WebSecurity.Business.Entities.Interfaces;
using T2.WebSecurity.Business.Entities.Search;
using T2.WebSecurity.Business.Entities.Search.Interfaces;
using T2.WebSecurity.Business;


using WebMatrix.WebData;
using System.Security.Cryptography;
using System.Web;
using System.Web.Security;
using T2.WebSecurity.Common;
using System.Activities;
using T2.WebSecurity.Business.Workflows;

namespace T2.WebSecurity
{
    public class SimpleMembershipProvider : ExtendedMembershipProvider
    {
        private const int TokenSizeInBytes = 0x10;
        private const string SaltString = "1111188888";

        private IBusinessService bs = new BusinessService();

        public SimpleMembershipProvider()
        {
            
        }

        public override void Initialize(string name, NameValueCollection config)
        {
            if (config == null)
                throw new ArgumentNullException("config");
            if (string.IsNullOrEmpty(name))
            {
                name = "T2.WebSecurity.SimpleMembershipProvider";
            }
            if (string.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", "The T Squared Software, Inc. providers are now working");
            }
            base.Initialize(name, config);

            ApplicationName = GetValueOrDefault(config, "tenantName", o => o.ToString(), @"Default");

            ApplicationName = GetValueOrDefault(config, "applicationName", o => o.ToString(), @"Default");

            this.ConnectionStringName = GetValueOrDefault(config, "connectionStringName", o => o.ToString(), string.Empty);
            //adapterFactory.Initialize(ConnectionStringName);

            this.enablePasswordRetrieval = GetValueOrDefault(config, "enablePasswordRetrieval", Convert.ToBoolean, false);
            this.passwordReset = GetValueOrDefault(config, "enablePasswordReset", Convert.ToBoolean, true);
            this.requiresQuestionAndAnswer = GetValueOrDefault(config, "requiresQuestionAndAnswer", Convert.ToBoolean, false);
            this.requiresUniqueEmail = GetValueOrDefault(config, "requiresUniqueEmail", Convert.ToBoolean, true);
            this.maxInvalidPasswordAttempts = GetValueOrDefault(config, "maxInvalidPasswordAttempts", Convert.ToInt32, 3);
            this.passwordAttemptWindow = GetValueOrDefault(config, "passwordAttemptWindow", Convert.ToInt32, 10);
            this.passwordFormat = GetValueOrDefault(config, "passwordFormat", o =>
            {
                MembershipPasswordFormat format;
                return Enum.TryParse(o.ToString(), true, out format) ? format : MembershipPasswordFormat.Hashed;
            }, MembershipPasswordFormat.Hashed);
            this.minRequiredPasswordLength = GetValueOrDefault(config, "minRequiredPasswordLength", Convert.ToInt32, 6);
            this.minRequiredNonAlphanumericCharacters = GetValueOrDefault(config, "minRequiredNonalphanumericCharacters",
                                                                          Convert.ToInt32, 1);
            this.passwordStrengthRegularExpression = GetValueOrDefault(config, "passwordStrengthRegularExpression",
                                                                       o => o.ToString(), string.Empty);
            this.HashAlgorithmType = GetValueOrDefault(config, "hashAlgorithmType", o => o.ToString(), "SHA1");

            config.Remove("name");
            config.Remove("description");
            config.Remove("applicationName");
            config.Remove("connectionStringName");
            config.Remove("enablePasswordRetrieval");
            config.Remove("enablePasswordReset");
            config.Remove("requiresQuestionAndAnswer");
            config.Remove("requiresUniqueEmail");
            config.Remove("maxInvalidPasswordAttempts");
            config.Remove("passwordAttemptWindow");
            config.Remove("passwordFormat");
            config.Remove("minRequiredPasswordLength");
            config.Remove("minRequiredNonalphanumericCharacters");
            config.Remove("passwordStrengthRegularExpression");
            config.Remove("hashAlgorithmType");
            config.Remove("tenantName");

            if (config.Count <= 0)
            {
                //this.isInitialized = true;
                return;
            }
            var key = config.GetKey(0);
            if (string.IsNullOrEmpty(key))
                //this.isInitialized = true;
                return;

            throw new ProviderException(string.Format(CultureInfo.CurrentCulture,
                                                      "The membership provider does not recognize the configuration attribute {0}.",
                                                      key));
        }

        private static T GetValueOrDefault<T>(NameValueCollection nvc, string key, Func<object, T> converter, T defaultIfNull)
        {
            var val = nvc[key];

            if (val == null)
                return defaultIfNull;

            try
            {
                return converter(val);
            }
            catch
            {
                return defaultIfNull;
            }
        }

        public string ConnectionStringName { get; set; }

        public string HashAlgorithmType { get; set; }

        private bool passwordReset;

        private bool enablePasswordRetrieval;

        private int numberOfUsersOnline;

        private int maxInvalidPasswordAttempts;

        private int minRequiredNonAlphanumericCharacters;

        private int minRequiredPasswordLength;

        private int passwordAttemptWindow;

        private string passwordStrengthRegularExpression;

        private bool requiresQuestionAndAnswer;

        private System.Web.Security.MembershipPasswordFormat passwordFormat;

        private bool requiresUniqueEmail;

        private string applicationName;
        public override string ApplicationName
        {
            get
            {
                return applicationName;
            }
            set
            {
                applicationName = value;
            }
        }

        public override bool ConfirmAccount(string accountConfirmationToken)
        {
            //This will lookup the Membership table record by the accountConfirmationToken 
            //and if found it will set the IsConfirmed field to true
            IMembershipSearch_biz param = new MembershipSearch_biz();
            param.Action = "Search";
            param.PageNumber = 1;
            param.PageSize = 10;
            param.SortColumn = "MembershipID";
            param.SortType = "asc";
            param.ConfirmationToken = accountConfirmationToken;
            
            List<IMembership_biz> retVal = bs.MembershipController_Search(param, true, true);

            if (retVal.Count == 0)
            {
                return false;
            }

            // make active
            this.UnlockUser(GetUserByUserID(retVal.FirstOrDefault().UserId).UserName);

            IMembership_biz paramSet = retVal.FirstOrDefault();
            paramSet.Action = "Update";
            paramSet.IsConfirmed = true;
            paramSet.ModifiedBy = "system";//Membership.GetUser().UserName;
            paramSet.ModifiedDt = DateTime.Now;
            IDictionary<string,int> retVals = bs.MembershipController_Set(paramSet);

            if (retVals.Count == 0)
            {
                var ret = retVals.ToList().Select(s => new { Key = s.Key, Value = s.Value });
                Int32 retInt = ret.Where(z => z.Key == "Return_Value").Select(m => m.Value).FirstOrDefault();
                if (retInt == 1)
                {
                    return false;
                }
            }
            
            return true;
            
        }

        public override bool ConfirmAccount(string userName, string accountConfirmationToken)
        {
            //This will first lookup the User table record for the user and then attempt to find the correct accountConfirmationToken
            //If the membership record is found and confirmed then the IsConfirmed field is set to true
            //This will lookup the Membership table record by the accountConfirmationToken 
            //and if found it will set the IsConfirmed field to true
            IMembershipSearch_biz param = new MembershipSearch_biz();
            param.Action = "Search";
            param.ConfirmationToken = accountConfirmationToken;
            List<IMembership_biz> retVal = bs.MembershipController_Search(param, true, true);
            if (retVal.Count == 0)
            {
                return false;
            }
            // Now we can check the userName 
            string memUser = retVal.FirstOrDefault().UserProfile.UserName;
            if (userName.ToLower() != memUser.ToLower())
            {
                return false;
            }

            //Now we need to update the Membership record to show IsConfirmed = true
            IMembership_biz memberParam = retVal.FirstOrDefault();
            memberParam.IsConfirmed = true;
            IDictionary<string,int> r = bs.MembershipController_Set(memberParam);
            var ret = r.ToList().Select(s => new { Key = s.Key, Value = s.Value });
            Int32 retInt = ret.Where(z => z.Key == "Return_Value").Select(m => m.Value).FirstOrDefault();
            if (retInt == 1)
            {
                return true;
            }
            return false;
        }

        public override string CreateAccount(string userName, string password, bool requireConfirmationToken)
        {
            // Given a specific user record this will create the membership table record
            // If requireConfirmationToken is set to true then it will return the token created here
            //First we need to get the  UserProfile
            if (userName == null)
            {
                throw new ApplicationException("User name parameter was  null");
            }

            IUserProfile_biz userParam = GetUserByName(userName);
            if (userParam == null)
            {
                throw new MissingMemberException("User: " + userName + " not found");
            }

            if (password == null)
            {
                throw new ApplicationException("Password parameter was null");
            }

            // Now let's check the account to see if it already exists.
            if (userParam.Membership_List.Count > 0)
            {
                throw new ApplicationException("Account already exist");
            }

            // Ok now lets add the account
            IMembership_biz memberParam = new Membership_biz();
            memberParam.Action = "Add";
            memberParam.ConfirmationToken = GenerateToken();
            memberParam.CreatedBy = "System";
            memberParam.CreatedDt = System.DateTime.Now;
            memberParam.EmailAccount = "find the email account";
            memberParam.IsConfirmed = false;
            //memberParam.LastPasswordFailureDate = 
            memberParam.ModifiedBy = "System";
            memberParam.ModifiedDt = System.DateTime.Now;
            
            memberParam.PasswordAnswer = "Default";
            memberParam.PasswordChangedDate = System.DateTime.Now;
            memberParam.PasswordFailuresSinceLastSuccess = 0;
            memberParam.PasswordQuestionID = 1;
            CryptoHelper ch = new CryptoHelper();
            String myPass = ch.EncryptStringAES(password, memberParam.PasswordAnswer, SaltString); 

            memberParam.Password = myPass;
            memberParam.PasswordSalt = SaltString; //ch.GetGeneratedSalt();
            memberParam.PasswordVerificationToken = GenerateToken();
            memberParam.PasswordVerificationTokenExpirationDate = DateTime.Now.AddHours(24);
            memberParam.UserId = userParam.UserId;
            IDictionary<string, int> r = bs.MembershipController_Set(memberParam);
            var ret = r.ToList().Select(s => new { Key = s.Key, Value = s.Value });
            Int32 retVal = ret.Where(z => z.Key == "Return_Value").Select(m => m.Value).FirstOrDefault();
            if (retVal == 1 && requireConfirmationToken)
            {
                return memberParam.ConfirmationToken;
            }
            else if (retVal == 1)
            {
                return string.Empty;
            }
            else
            {
               
                throw new ApplicationException("Create Account failed: " + bs.ValidationErrors.FirstOrDefault());
            }
        }

        public override string CreateUserAndAccount(string _userName, string _password, bool _requireConfirmation, IDictionary<string, object> _values)
        {
            IDictionary<string, object> input = new Dictionary<string, object>();
            input.Add("BusinessService", bs);
            input.Add("UserName", _userName);
            input.Add("Password", _password);
            IDictionary<string, object> output = WorkflowInvoker.Invoke(new UserProfileCreateCheckActivity(), input);
            if(output!=null)
                if (output.ContainsKey("CheckStatus"))
                {
                    MembershipCreateStatus status = (MembershipCreateStatus)output["CheckStatus"];
                    if(status!=MembershipCreateStatus.Success)
                        throw new MembershipCreateUserException(status);
                }

            string _emailValue = String.Empty;

            string _passwordQuestion = String.Empty;

            string _passwordAnswer = String.Empty;

            string _isApprovedTemp = String.Empty;

            object _providerUserKey = null;

            bool _isApproved = false;

            
            if (_values != null)
            {
                _emailValue = GetKVPByName(_values, "email").Value.ToString();
                if (String.IsNullOrEmpty(_emailValue))
                {
                    _emailValue = "";
                }
                

                if (_values != null)
                {
                    _passwordQuestion = GetKVPByName(_values, "passwordquestion").Value.ToString();

                    if (String.IsNullOrEmpty(_passwordQuestion))
                    {
                        _passwordQuestion = "1";
                    }
                    //else
                    //{
                    //    IPasswordQuestion_biz tempPQ = this.GetPasswordQuestionByDesc(_passwordQuestion);
                    //    _passwordQuestion = tempPQ.PasswordQuestionID.ToString();
                    //}
                }
                else
                {
                    _passwordQuestion = "1";
                }


                if (_values != null)
                {
                    _passwordAnswer = GetKVPByName(_values, "passwordanswer").Value.ToString();
                    if (String.IsNullOrEmpty(_passwordAnswer))
                    {
                        _passwordAnswer = String.Empty;
                    }
                }
                else
                {
                    _passwordAnswer = String.Empty;
                }

                if (_values != null)
                {
                    _isApprovedTemp = GetKVPByName(_values, "isapproved").Value.ToString();

                    if (String.IsNullOrEmpty(_isApprovedTemp))
                    {
                        _isApprovedTemp = "false";
                    }
                }
                else
                {
                    _isApprovedTemp = "false";
                }


                _isApproved = Convert.ToBoolean(_isApprovedTemp);

                _providerUserKey = GetKVPByName(_values, "provideruserkey").Value.ToString();

                if (_providerUserKey == null)
                {
                    IOAuthMembership_biz puk = new OAuthMembership_biz();
                    _providerUserKey = puk;
                }
            }
               

                

                // Call Encryption method
            CryptoHelper ch = new CryptoHelper();
            string _passEncrypt = ch.EncryptStringAES(_password, _passwordAnswer, SaltString);   

                string _lastName = GetKVPByName(_values, "lastname").Value.ToString();
                string _firstName = GetKVPByName(_values, "firstname").Value.ToString();
                string _address = GetKVPByName(_values, "address").Value.ToString();
                string _city = GetKVPByName(_values, "city").Value.ToString();
                string _region = GetKVPByName(_values, "region").Value.ToString();
                string _postalCode = GetKVPByName(_values, "postalcode").Value.ToString();
                string _cellPhone = GetKVPByName(_values, "cellphone").Value.ToString();
                string _officePhone = GetKVPByName(_values, "officephone").Value.ToString();
                string _title = GetKVPByName(_values, "title").Value.ToString();
                int _userid = 0;
                try
                {
                    IUserProfile_biz retCreateUser =
                        AddUser(_userName, _firstName, _lastName, _address, _city, _region, _postalCode, _cellPhone, _officePhone, _title);
                    _userid = retCreateUser.UserId;
                }
                catch (Exception ex)
                {
                    throw new MembershipCreateUserException(MembershipCreateStatus.UserRejected);
                }
                
                    //Now it is ok to create the account
                IMembership_biz retValMember = this.AddAccount(_emailValue, _passEncrypt, _passwordAnswer, Convert.ToInt32(_passwordQuestion), SaltString, _userid);

                if (_requireConfirmation)
                {
                    return retValMember.ConfirmationToken;
                }

                return String.Empty;
            

            
            
        }

        private IMembership_biz AddAccount(string _email, string _encryptedPassword, string _passwordAnswer, int _passwordQuestionID, string _passwordSalt, int _userid)
        {
            IMembership_biz param = new Membership_biz();
            param.Action = MyEnum.Actions.Add.ToString();
            param.ConfirmationToken = GenerateToken();
            param.CreatedBy = Membership.GetUser() == null ? "System" : Membership.GetUser().UserName;
            param.CreatedDt = System.DateTime.Now;
            param.ModifiedBy = Membership.GetUser() == null ? "System" : Membership.GetUser().UserName;
            param.ModifiedDt = System.DateTime.Now;
            param.EmailAccount = _email;
            param.IsConfirmed = false;
            param.LastLockoutDate = Convert.ToDateTime("01/01/1800");
            param.LastLoginDate = Convert.ToDateTime("01/01/1800");
            param.LastPasswordFailureDate = Convert.ToDateTime("01/01/1800");
            param.Password = _encryptedPassword;
            param.PasswordAnswer = _passwordAnswer;
            param.PasswordChangedDate = System.DateTime.Now;
            param.PasswordFailuresSinceLastSuccess = 0;
            param.PasswordQuestionID = _passwordQuestionID;
            param.PasswordSalt = _passwordSalt;
            param.PasswordVerificationToken = GenerateToken();
            param.PasswordVerificationTokenExpirationDate = System.DateTime.Now.AddDays(1);
            param.UserId = _userid;
            IDictionary<string, int> r = bs.MembershipController_Set(param);
            var ret = r.ToList().Select(s => new { Key = s.Key, Value = s.Value });
            var priKey = ret.Where(z => z.Key == "PKMembershipID").Select(m => m.Value);
            Int32 priKeyVal = Convert.ToInt32(priKey.FirstOrDefault());
            param.Action = MyEnum.Actions.GetOne.ToString();
            param.MembershipID = priKeyVal;
            List<IMembership_biz> retVal = bs.MembershipController_Get(param, false, false);
            return retVal.FirstOrDefault();
            
        
        }

        private IUserProfile_biz AddUser(string _userName, string _firstName, String _lastName,
                                string _address, string _city, string _region, string _postalCode,
                                string _cellPhone, string _officePhone, string _title)
        { 
            IUserProfile_biz  param = new UserProfile_biz();
            param.Action = MyEnum.Actions.Add.ToString();
            param.UserName = _userName;
            param.FirstName = _firstName;
            param.LastName = _lastName;
            param.Address = _address;
            param.City = _city;
            param.Region = _region;
            param.PostalCode = _postalCode;
            param.CellPhone = _cellPhone;
            param.OfficePhone = _officePhone;
            param.Title = _title;
            param.CreatedBy = Membership.GetUser() == null ? "System" : Membership.GetUser().UserName;
            param.CreatedDt = System.DateTime.Now;
            param.ModifiedBy = Membership.GetUser() == null ? "System" : Membership.GetUser().UserName;
            param.ModifiedDt = System.DateTime.Now;
            IDictionary<string, int> r = bs.UserProfileController_Set(param);
            var ret = r.ToList().Select(s => new { Key = s.Key, Value = s.Value });
            var priKey = ret.Where(z => z.Key == "PKUserId").Select(m => m.Value);
            Int32 priKeyVal = Convert.ToInt32(priKey.FirstOrDefault());
            param.Action = MyEnum.Actions.GetOne.ToString();
            param.UserId = priKeyVal;
            List<IUserProfile_biz> retVal = bs.UserProfileController_Get(param, false, false);
            return retVal.FirstOrDefault();
        }


        public override bool DeleteAccount(string _userName)
        {
            // Given a specific username this will delete the record if found and return true
            IUserProfile_biz myUser = GetUserByName(_userName);
            myUser.Action = "Remove";
            IDictionary<string,int> r = bs.UserProfileController_Set(myUser);
            var ret = r.ToList().Select(s => new { Key = s.Key, Value = s.Value });
            Int32 retVal = ret.Where(z => z.Key == "Return_Value").Select(m => m.Value).FirstOrDefault();
            return Convert.ToBoolean(retVal);
            
        }

        public override string GeneratePasswordResetToken(string _userName, int _tokenExpirationInMinutesFromNow)
        {
            //Given that the time from now adding the tokenExpirationInMinutesFromNow is updated in the database membership table
            // Create a token update the Membership table and return this tokey
            if (_tokenExpirationInMinutesFromNow <= 0)
            {
                _tokenExpirationInMinutesFromNow = 86400;
            }

            IUserProfile_biz param = this.GetUserByName(_userName);
            IMembership_biz memParam = param.Membership_List.FirstOrDefault();
            if (memParam == null)
            {
                throw new ApplicationException("No Account Found");
            }
            // Now we can update the memParam to the new password token and token expiration
            memParam.Action = "Update";
            memParam.PasswordChangedDate = DateTime.Now;
            memParam.PasswordVerificationToken = GenerateToken();
            memParam.PasswordVerificationTokenExpirationDate = DateTime.Now.AddMinutes(_tokenExpirationInMinutesFromNow);
            IDictionary<string,int> r = bs.MembershipController_Set(memParam);
            var ret = r.ToList().Select(s => new { Key = s.Key, Value = s.Value });
            Int32 retVal = ret.Where(z => z.Key == "Return_Value").Select(m => m.Value).FirstOrDefault();
            if (retVal == 1)
            {
                return memParam.PasswordVerificationToken;
            }
            else if (retVal == 0)
            {
                throw new ApplicationException("Update token failed");
            }
            else
            {
                throw new ApplicationException(bs.ValidationErrors.FirstOrDefault().ToString());
            }
            
        }

        public override ICollection<OAuthAccountData> GetAccountsForUser(string userName)
        {
            //Get all of the external accounts for a user and return it
            IUserProfile_biz myUser = this.GetUserByName(userName);

            ICollection<OAuthAccountData> retVal = new List<OAuthAccountData>();
            foreach (OAuthMembership_biz item in myUser.OAuthMembership_List)
            {
                OAuthAccountData ad = new OAuthAccountData(item.Provider,item.ProviderUserID);
                retVal.Add(ad);
            }
            return retVal;
        }

        public override DateTime GetCreateDate(string userName)
        {
            // Return the created date of a user given the userName
            IUserProfile_biz myUser = this.GetUserByName(userName);
            if (myUser != null)
            {
                return myUser.CreatedDt;
            }
            
            // if the user was not found then throw an exception
            throw new ApplicationException("User  was not found");
        }

        public override DateTime GetLastPasswordFailureDate(string userName)
        {
            // Given the userName find a user record and  relate it to a Membership record and return the 
            // LastPasswordFailuredate
            IUserProfile_biz myUser = this.GetUserByName(userName);
            if (myUser == null)
            {
                throw new ApplicationException("User was not found");

            }
            IMembership_biz memberParam = myUser.Membership_List.FirstOrDefault();
            if (memberParam == null)
            {
                throw new ApplicationException("User was found, but had no accounts");
            }
            return memberParam.LastPasswordFailureDate;
            
        }

        public override DateTime GetPasswordChangedDate(string userName)
        {
            // Given the userName find a user record and  relate it to a Membership record and return the 
            // PasswordChangedDate

            IUserProfile_biz myUser = this.GetUserByName(userName);
            if (myUser == null)
            {
                throw new ApplicationException("User was not found");

            }
            IMembership_biz memberParam = myUser.Membership_List.FirstOrDefault();
            if (memberParam == null)
            {
                throw new ApplicationException("User was found, but had no accounts");
            }
            return memberParam.PasswordChangedDate;
            
        }

        public override int GetPasswordFailuresSinceLastSuccess(string userName)
        {
            // Given the userName find a user record and  relate it to a Membership record and return the 
            // PasswordFailuresSinceLastSuccess
            IUserProfile_biz myUser = this.GetUserByName(userName);
            if (myUser == null)
            {
                throw new ApplicationException("User was not found");

            }
            IMembership_biz memberParam = myUser.Membership_List.FirstOrDefault();
            if (memberParam == null)
            {
                throw new ApplicationException("User was found, but had no accounts");
            }
            return memberParam.PasswordFailuresSinceLastSuccess;
        }

        public override int GetUserIdFromPasswordResetToken(string token)
        {
            IMembershipSearch_biz param = new MembershipSearch_biz();
            param.Action = "Search";
            param.PasswordVerificationToken = token;
            List<IMembership_biz> memberList = bs.MembershipController_Search(param, true, true);
            if (memberList.Count == 0)
            {
                throw new ApplicationException("Account not found");
            }
            if (memberList.Count != 1)
            {
                throw new ApplicationException("Duplicate password token found");
            }
            
            
            return memberList.FirstOrDefault().UserId;
        }

        public override bool IsConfirmed(string userName)
        {
            // Given the userName find a user record and  relate it to a Membership record and return the 
            // IsConfirmed field

            IUserProfile_biz myUser = this.GetUserByName(userName);
            if (myUser == null)
            {
                throw new ApplicationException("User was not found");

            }
            IMembership_biz memberParam = myUser.Membership_List.FirstOrDefault();
            if (memberParam == null)
            {
                throw new ApplicationException("User was found, but had no accounts");
            }
            return memberParam.IsConfirmed;

            
        }

        public override bool ResetPasswordWithToken(string token, string newPassword)
        {
            //Given a password token reset the password with the newpassword parameter
            IMembershipSearch_biz param = new MembershipSearch_biz();
            param.Action = "Search";
            param.PageNumber = 1;
            param.PageSize = 10;
            param.SortColumn = "MembershipID";
            param.SortType = "asc";
            param.PasswordVerificationToken = token;

            List<IMembership_biz> retMembershipList = bs.MembershipController_Search(param, false, false);
            if (retMembershipList.Count == 0)
            { 
                throw new  ApplicationException("Account not found");
            }
            else if (retMembershipList.Count < 0)
            {
                throw new ApplicationException(bs.ValidationErrors.FirstOrDefault().ToString());
            }

            IMembership_biz retMember = retMembershipList.FirstOrDefault();
            // Call Encryption method
            CryptoHelper ch = new CryptoHelper();
            string _newPassEncrypt = ch.EncryptStringAES(newPassword, retMember.PasswordAnswer, SaltString);

            IMembership_biz updateParam = retMembershipList.FirstOrDefault();
            updateParam.Action = "Update";
            updateParam.Password = _newPassEncrypt;
            updateParam.ModifiedDt = DateTime.Now;
            updateParam.ModifiedBy = Membership.GetUser().UserName;

            IDictionary<string,int> r = bs.MembershipController_Set(updateParam);
            var ret = r.ToList().Select(s => new { Key = s.Key, Value = s.Value });
            Int32 retVal = ret.Where(z => z.Key == "Return_Value").Select(m => m.Value).FirstOrDefault();
            if (retVal == 0)
            {
                return false;
            }
            else if (retVal < 0)
            {
                throw new ApplicationException(bs.ValidationErrors.FirstOrDefault().ToString());
            }


            return true;
        }

        

        public override bool ChangePassword(string _username, string _oldPassword, string _newPassword)
        {
            // Given a username find the user record and  the  membership record
            // If the old password matches then reset it to the newPassword parameter and return true
            IUserProfile_biz myUser = this.GetUserByName(_username);
            if (myUser == null)
            {
                throw new ApplicationException("User was not found");

            }
            IMembership_biz memberParam = myUser.Membership_List.FirstOrDefault();

            //
            CryptoHelper ch = new CryptoHelper();
            String oldPassDec = ch.DecryptStringAES(memberParam.Password, memberParam.PasswordAnswer, SaltString);
            String newPassEnc = ch.EncryptStringAES(_newPassword, memberParam.PasswordAnswer, SaltString);

            if (memberParam == null)
            {
                throw new ApplicationException("User was found, but had no accounts");
            }
            if (_oldPassword != oldPassDec)
            {
                throw new ApplicationException("Password did not match");
            }
            memberParam.Action = "Update";
            memberParam.Password = newPassEnc;
            memberParam.ModifiedBy = "System";
            memberParam.ModifiedDt = System.DateTime.Now;
            memberParam.PasswordSalt = ch.SaltString;
            IDictionary<string,int> r = bs.MembershipController_Set(memberParam);
            var ret = r.ToList().Select(s => new { Key = s.Key, Value = s.Value });
            Int32 retVal = ret.Where(z => z.Key == "Return_Value").Select(m => m.Value).FirstOrDefault();
            if (retVal < 0)
            {
                throw new ApplicationException(bs.ValidationErrors.FirstOrDefault().ToString());
            }
            else if (retVal == 0)
            {
                return false;
            }
            return true;
        }

        public override bool ChangePasswordQuestionAndAnswer(string _username, string _password, string _newPasswordQuestion, string _newPasswordAnswer)
        {
            // Find the username and membership record given the password
            //Then match the PasswordQuestion table with a PasswordQuestion and return the PasswordQuestionID 
            //Check the membership token to see if it is the same and if not update both the PasswordQuestionID and the PasswordAnswer in the table

            IUserProfile_biz userParam = this.GetUserByName(_username);
            if (userParam == null)
            {
                throw new ApplicationException("User could not be found");
            }
            if (userParam.Membership_List == null || userParam.Membership_List.Count == 0)
            {
                throw new ApplicationException("User was found but no accounts exist");
            }
            IMembership_biz memberParam = userParam.Membership_List.FirstOrDefault();

            // Call Decription method
            CryptoHelper ch = new CryptoHelper();
            string _passwordEnc = ch.EncryptStringAES(_password, memberParam.PasswordAnswer, SaltString);

            if (memberParam.Password != _passwordEnc)
            {
                throw new ApplicationException("Password does not match");
            }
            memberParam.Action = "Update";
            

            IPasswordQuestion_biz passNewParam = this.GetPasswordQuestionByDesc(_newPasswordQuestion);
            if (passNewParam == null)
            {
                throw new ApplicationException("Password Question could not be found");
            }
            memberParam.PasswordQuestionID = passNewParam.PasswordQuestionID;
            memberParam.PasswordAnswer = _newPasswordAnswer;
            IDictionary<string,int> r = bs.MembershipController_Set(memberParam);
            var ret = r.ToList().Select(s => new { Key = s.Key, Value = s.Value });
            Int32 retVal = ret.Where(z => z.Key == "Return_Value").Select(m => m.Value).FirstOrDefault();
            if (retVal < 0)
            {
                throw new ApplicationException(bs.ValidationErrors.FirstOrDefault().ToString());
            }
            else if (retVal == 0)
            {
                return false;
            }

            
            return true;
        }

        public override System.Web.Security.MembershipUser CreateUser(string _username, string _password, string _email, string _passwordQuestion, string _passwordAnswer, bool _isApproved, object _providerUserKey, out System.Web.Security.MembershipCreateStatus _status)
        {
            //Given the parameters above create a new user record and a membership record then return a MembershipUser object
            // This is  also used  for the OAuthMembership record
            // First thing is  to make sure we do not have a user

            
            IUserProfile_biz userParam = this.GetUserByName(_username);
            if (userParam != null)
            {
                _status = MembershipCreateStatus.DuplicateUserName;

                return null;
            }
            else
            {
                userParam = new UserProfile_biz();
            }
            userParam.Action = "Add";
            IApplication_biz appParam = GetApplicationByName(this.ApplicationName);
            if (appParam == null)
            {
                throw new ProviderException("Application does not exist in repository");
            }
            //userParam.ApplicationID = appParam.ApplicationID;
            userParam.CreatedBy = "System";
            userParam.CreatedDt = DateTime.Now;
            userParam.FirstName = String.Empty;
            userParam.LastName = String.Empty;
            userParam.ModifiedBy = String.Empty;
            userParam.ModifiedDt = DateTime.Now;
            userParam.UserName = _username;
            IDictionary<string,int> r = bs.UserProfileController_Set(userParam);
            var ret = r.ToList().Select(s => new { Key = s.Key, Value = s.Value });
            Int32 userRetVal = ret.Where(z => z.Key == "Return_Value").Select(m => m.Value).FirstOrDefault();
            if (userRetVal == 0)
            {
                _status = System.Web.Security.MembershipCreateStatus.UserRejected;
                return null;
            }
            if (userRetVal <= 0)
            {
                throw new ProviderException(bs.ValidationErrors.FirstOrDefault().ToString());
            }
            //Now we have a new user  we can get the userprofile from the database
            IUserProfile_biz userSearchRetVal = this.GetUserByName(_username);
            if (userSearchRetVal == null)
            {
                throw new ProviderException("User was created but search could not find it");

            }
            //Ok now we have the record
            //The first thing here is to associate it with the application
            IApplicationUser_biz appUserParam = new ApplicationUser_biz();
            appUserParam.Action = "Add";
            appUserParam.ApplicationID = appParam.ApplicationID;
            appUserParam.UserId = userSearchRetVal.UserId;
            appUserParam.CreatedBy = "System";
            appUserParam.CreatedDt = System.DateTime.Now;
            appUserParam.ModifiedBy = "System";
            appUserParam.ModifiedDt = System.DateTime.Now;

            IDictionary<string,int> r2 = bs.ApplicationUserController_Set(appUserParam);
            var ret2 = r2.ToList().Select(s  => new {Key=s.Key, Value = s.Value}) ;
            Int32 appUserRetVal = ret2.Where(z => z.Key == "Return_Value").Select(m => m.Value).FirstOrDefault();
            if (appUserRetVal <= 0)
            {
                throw new ProviderException("Appliation User Association was not setup");
            }

            MembershipUser mu = this.CreateMembershipUser(userSearchRetVal);
            _status = System.Web.Security.MembershipCreateStatus.Success;
            return mu;
        }

        public override bool DeleteUser(string _username, bool deleteAllRelatedData)
        {
            //Given a username find the user record and delete all of the related table data in membership and userinrole
            Int32 retVals = 0;
            IUserProfile_biz retVal = this.GetUserByName(_username);

            using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.Serializable }))
            {

                foreach (IMembership_biz memberItem in retVal.Membership_List)
                {
                    memberItem.Action = "Remove";
                    IDictionary<string, int> r = bs.MembershipController_Set(memberItem);
                    var ret2 = r.ToList().Select(s => new { Key = s.Key, Value = s.Value });
                    Int32 retVal2 = ret2.Where(z => z.Key == "Return_Value").Select(m => m.Value).FirstOrDefault();
                    retVals += retVal2;
                }
                foreach (IOAuthMembership_biz oAuthItem in retVal.OAuthMembership_List)
                {
                    oAuthItem.Action = "Remove";
                    IDictionary<string, int> r2 = bs.OAuthMembershipController_Set(oAuthItem);
                    var ret2 = r2.ToList().Select(s => new { Key = s.Key, Value = s.Value });
                    Int32 oAuthRetVal = ret2.Where(z => z.Key == "Return_Value").Select(m => m.Value).FirstOrDefault();
                    retVals += oAuthRetVal;
                }
                foreach (IApplicationUser_biz appUserItem in retVal.ApplicationUser_List)
                {
                    appUserItem.Action = "Remove";
                    IDictionary<string, int> r3 = bs.ApplicationUserController_Set(appUserItem);
                    var ret3 = r3.ToList().Select(s => new { Key = s.Key, Value = s.Value });
                    Int32 appUserRetVal = ret3.Where(z => z.Key == "Return_Value").Select(m => m.Value).FirstOrDefault();
                    retVals += appUserRetVal;
                }
                foreach (IUsersInRoles_biz userInRoleItem in retVal.UsersInRoles_List)
                {
                    userInRoleItem.Action = "Remove";
                    IDictionary<string, int> r4 = bs.UsersInRolesController_Set(userInRoleItem);
                    var ret4 = r4.ToList().Select(s => new { Key = s.Key, Value = s.Value });
                    Int32 userInRoleRetVal = ret4.Where(z => z.Key == "Return_Value").Select(m => m.Value).FirstOrDefault();
                    retVals += userInRoleRetVal;
                }

                retVal.Action = "Remove";
                IDictionary<string, int> r5 = bs.UserProfileController_Set(retVal);
                var ret5 = r5.ToList().Select(s => new { Key = s.Key, Value = s.Value });
                Int32 upcRetVal = ret5.Where(z => z.Key == "Return_Value").Select(m => m.Value).FirstOrDefault();
                retVals += upcRetVal;

                scope.Complete();
            }
            return retVals > 0;
        }

        public override bool EnablePasswordReset
        {
            get { return passwordReset; }
        }

        public override bool EnablePasswordRetrieval
        {
            get { return enablePasswordRetrieval; }
        }

        public override System.Web.Security.MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            // Given a email property match this to the user account and to the membership record 
            // Create a Membership user and add it to the collection
            IMembershipSearch_biz memberParam = new MembershipSearch_biz();
            memberParam.Action = "Search";
            memberParam.EmailAccount = emailToMatch;
            List<IMembership_biz> memberRetVal = bs.MembershipController_Search(memberParam, true, true);
            System.Web.Security.MembershipUserCollection retVal = new System.Web.Security.MembershipUserCollection();
            foreach (IMembership_biz item in memberRetVal)
            {
                System.Web.Security.MembershipUser tempUser = this.CreateMembershipUser(item.UserProfile);
                retVal.Add(tempUser);
            }

            
            totalRecords = retVal.Count;
            return retVal;
        }

        public override System.Web.Security.MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            // Given a username property match this to the user account and to the membership record 
            // Create a Membership user and add it to the collection
            IUserProfileSearch_biz userParam = new UserProfileSearch_biz();
            userParam.Action = "Search";
            userParam.UserName = usernameToMatch;
            userParam.PageNumber = pageIndex;
            userParam.PageSize = pageSize;
            userParam.SortColumn = "UserProfileID";
            userParam.SortType = "asc";
            List<IUserProfile_biz> userList = bs.UserProfileController_Search(userParam, true, true);
            System.Web.Security.MembershipUserCollection retVal = new System.Web.Security.MembershipUserCollection();
            foreach (IUserProfile_biz item in userList)
            {
                MembershipUser temp = CreateMembershipUser(item);
                retVal.Add(temp);
            }
            if (userList.Count > 0)
            {
                totalRecords = userList.FirstOrDefault().TotalRows;
            }
            else
            {
                totalRecords = 0;
            }
            return retVal;
        }

        public override System.Web.Security.MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            // Return all  of the users 
            // Create a Membership user and add it to the collection
            IUserProfile_biz userParam = new UserProfile_biz();
            userParam.Action = "GetAll";
            userParam.PageNumber = pageIndex;
            userParam.PageSize = pageSize;
            userParam.SortColumn = "UserProfileID";
            userParam.SortType = "asc";
            List<IUserProfile_biz> userList = bs.UserProfileController_Get(userParam, true, true);
            System.Web.Security.MembershipUserCollection retVal = new System.Web.Security.MembershipUserCollection();
            foreach (IUserProfile_biz item in userList)
            {
                MembershipUser temp = CreateMembershipUser(item);
                retVal.Add(temp);
            }
            if (userList.Count > 0)
            {
                totalRecords = userList.FirstOrDefault().TotalRows;
            }
            else
            {
                totalRecords = 0;
            }
            return retVal;
        }

        public override int GetNumberOfUsersOnline()
        {
            return numberOfUsersOnline;
        }

        public override string GetPassword(string username, string answer)
        {
            // Given a username find the matching user and membership records matching the passwordAnswer
            if (enablePasswordRetrieval)
            {
                IUserProfile_biz userParam = GetUserByName(username);
                if (userParam == null)
                {
                    throw new ProviderException("User was not found");
                }
                List<IMembership_biz> bizRetVal = userParam.Membership_List.Where(p => p.PasswordAnswer.ToLower() == answer.ToLower()).ToList();
                if (bizRetVal.Count == 0)
                {
                    throw new ProviderException("User was found but no account matched the answer provided");
                }
                else if (bizRetVal.Count > 1)
                {
                    throw new ProviderException("More than one account was encountered");
                }
                else
                {
                    // call decryption
                    string password = bizRetVal.FirstOrDefault().Password;
                    CryptoHelper ch = new CryptoHelper();
                    return ch.DecryptStringAES(password, answer, SaltString);
                }
            }
            else
            {
                throw new NotSupportedException();
            }
        }

        public override System.Web.Security.MembershipUser GetUser(string username, bool userIsOnline)
        {
            // Given a username and  a bool that the userIsOnline match the record in the database and retuurn a membershipuser
            IUserProfile_biz userVal = this.GetUserByName(username);
            if (userVal == null)
            {
                throw new ProviderException("User could not be found");
            }
            
            System.Web.Security.MembershipUser retVal = this.CreateMembershipUser(userVal);
            return retVal;
        }

        public override System.Web.Security.MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            // Given a OAuth provider username and  a bool that the userIsOnline match the record in the database and retuurn a membershipuser

            IOAuthMembershipSearch_biz oAuthParam = new OAuthMembershipSearch_biz();
            oAuthParam.Action = "Search";
            oAuthParam.PageNumber = 1;
            oAuthParam.PageSize = 10;
            oAuthParam.SortColumn = "OAuthMembershipID";
            oAuthParam.SortType = "asc";
            oAuthParam.Provider = providerUserKey.ToString();

            List<IOAuthMembership_biz> retList = bs.OAuthMembershipController_Search(oAuthParam, true, true);
            if (retList.Count == 0)
            {
                throw new ProviderException("OAuth provider was not found");

            }
            IUserProfile_biz tempUser = retList.FirstOrDefault().UserProfile;
            System.Web.Security.MembershipUser retVal = this.CreateMembershipUser(tempUser);
            return retVal;
        }

        public override string GetUserNameByEmail(string email)
        {
            //Given an email match this to a user and return the UserName property
            IMembershipSearch_biz memberParam = new MembershipSearch_biz();
            memberParam.PageNumber = 1;
            memberParam.PageSize = 10;
            memberParam.SortColumn = "MembershipID";
            memberParam.SortType = "asc";
            memberParam.Action = "Search";
            memberParam.EmailAccount = email;
            List<IMembership_biz> retValList = bs.MembershipController_Search(memberParam, true, true);
            if (retValList.Count == 0)
            {
                throw new ProviderException("Account for this email was not found");
            }
            if (retValList.Count > 1)
            {
                throw new ProviderException("More than one account was returned for this email");
            }
            return retValList.FirstOrDefault().UserProfile.UserName;
            
        }

        //Public Properties section

        public override int MaxInvalidPasswordAttempts
        {
            get { return maxInvalidPasswordAttempts; }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { return minRequiredNonAlphanumericCharacters; }
        }

        public override int MinRequiredPasswordLength
        {
            get { return minRequiredPasswordLength; }
        }

        public override int PasswordAttemptWindow
        {
            get { return passwordAttemptWindow; }
        }

        public override System.Web.Security.MembershipPasswordFormat PasswordFormat
        {
            get { return passwordFormat; }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { return passwordStrengthRegularExpression; }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { return requiresQuestionAndAnswer; }
        }

        public override bool RequiresUniqueEmail
        {
            get { return requiresUniqueEmail; }
        }

        public override string ResetPassword(string username, string answer)
        {
            // Given a user name and a password answer find a membership record and reset the password to 
            // A system generated password
            IUserProfile_biz temp = GetUserByName(username);
            if (temp == null)
            {
                throw new ProviderException("User was not found");
            }
            if (temp.Membership_List.Count == 0)
            {
                throw new ProviderException("The user was found, but no account exists");
            }
            List<IMembership_biz> membershipList = temp.Membership_List.Where(p => p.PasswordAnswer.ToLower() == answer.ToLower()).ToList();
            if (membershipList.Count == 0)
            {
                throw new ProviderException("Sorry no account matching that answer was found");
            }
            IMembership_biz memberParam = membershipList.FirstOrDefault();
            memberParam.Action = "Update";
            
            
            // call encryption
            string generatedPass = GenerateToken();

            CryptoHelper ch = new CryptoHelper();
            memberParam.Password = ch.EncryptStringAES(generatedPass, memberParam.PasswordAnswer, SaltString);

            IDictionary<string,int> r = bs.MembershipController_Set(memberParam);
            var ret = r.ToList().Select(s => new { Key = s.Key, Value = s.Value });
            Int32 retVal = ret.Where(z => z.Key == "Return_Value").Select(m => m.Value).FirstOrDefault();
            if (retVal == 0)
            {
                throw new ProviderException("Member was found but the update failed. Please try again later");
            }
            if (retVal == -1)
            {
                throw new ProviderException(bs.ValidationErrors.FirstOrDefault().ToString());
            }

            return generatedPass;
        }

        public override bool UnlockUser(string userName)
        {
            //Given a username find the record and set the IsActive to true
            IUserProfile_biz param = GetUserByName(userName);
            param.Action = "Update";
            param.IsActive = true;
            IDictionary<string,int> r = bs.UserProfileController_Set(param);
            var ret = r.ToList().Select(s => new { Key = s.Key, Value = s.Value });
            Int32 retVal = ret.Where(z => z.Key == "Return_Value").Select(m => m.Value).FirstOrDefault();
            return Convert.ToBoolean(retVal);

        }

        public override void UpdateUser(System.Web.Security.MembershipUser user)
        {
            //Given a MembershipUser object update the user record in the database
            IUserProfile_biz param = GetUserByName(user.UserName);
            if (param == null)
            {
                throw new ProviderException("Account was not found for this user");
            }
            //Everything here is updated at the account level
            if (param.Membership_List.Count == 0)
            {
                throw new ProviderException("User was found but no account exists.");
            }
            if (param.Membership_List.Count > 1)
            {
                throw new ProviderException("User has more than one account");
            }

            IMembership_biz memberParam = param.Membership_List.FirstOrDefault();
            memberParam.Action = "Update";
            memberParam.EmailAccount = user.Email;
            memberParam.IsConfirmed = user.IsApproved;
            memberParam.LastLockoutDate = user.LastLockoutDate;
            memberParam.LastLoginDate = user.LastLoginDate;
            memberParam.Password = user.GetPassword();
            IDictionary<string, int> r = bs.MembershipController_Set(memberParam);
            var ret = r.ToList().Select(s => new { Key = s.Key, Value = s.Value });
            Int32 retVal = ret.Where(z => z.Key == "Return_Value").Select(m => m.Value).FirstOrDefault();
            if (retVal <= 0)
            {
                throw new ProviderException("User was not updated");
            }

        }

        public override bool ValidateUser(string username, string password)
        {
            //Given a user name determine the user record and compare the password
            // If found return true
            IUserProfile_biz retVal = GetUserByName(username);
            if (retVal == null)
            {
                return false;
            }
            if (retVal.Membership_List.Count == 0)
            {
                return false;
            }
            if (!retVal.IsActive)
            {
                return false;
            }

            // call encrypt
            CryptoHelper ch = new CryptoHelper();
            //string encPassword = ch.EncryptStringAES(password, retVal.Membership_List.FirstOrDefault().PasswordAnswer, SaltString);
            string decPassword = ch.DecryptStringAES(retVal.Membership_List.FirstOrDefault().Password, retVal.Membership_List.FirstOrDefault().PasswordAnswer, SaltString);
            //var memberItem = retVal.Membership_List.Where(p => p.Password == encPassword).FirstOrDefault();
            if (!decPassword.Equals(password))
            {
                return false;
            }
            return true;

        }

        public List<IPasswordQuestion_biz> GetPasswordQuestions()
        {
            PasswordQuestion_biz param = new PasswordQuestion_biz();
            param.Action = "GetAll";
            param.SortColumn = "PasswordQuestionID";
            param.SortType = "asc";
            param.PageNumber = 1;
            param.PageSize = 99999;
            List<IPasswordQuestion_biz> retValBiz = bs.PasswordQuestionController_Get(param, true, true);

            return retValBiz;
        }

        private string GenerateToken()
        {
            using (var provider = new RNGCryptoServiceProvider())
            {
                return GenerateToken(provider);
            }
        }

        internal static string GenerateToken(RandomNumberGenerator generator)
        {
            var data = new byte[0x10];
            generator.GetBytes(data);
            return HttpServerUtility.UrlTokenEncode(data);
        }

        private IUserProfile_biz GetUserByUserID(Int32 userID)
        {
            IUserProfile_biz param = new UserProfile_biz();
            param.Action = "GetOne";
            param.UserId = userID;
            param.PageNumber = 1;
            param.PageSize = 10;
            param.SortColumn = "ApplicationID";
            param.SortType = "asc";
            List<IUserProfile_biz> retVal = bs.UserProfileController_Get(param, true, true);
            if (retVal.Count == 0)
            {
                return null;
            }
            else
            {
                return retVal.FirstOrDefault();
            }
        
        }

        private IUserProfile_biz GetUserByName(string username)
        {
            IUserProfileSearch_biz paramSearch = new UserProfileSearch_biz();
            paramSearch.Action = "Search";
            paramSearch.UserName = username;
            paramSearch.LastName = string.Empty;
            paramSearch.FirstName = string.Empty;
            paramSearch.Address = String.Empty;
            paramSearch.City = String.Empty;
            paramSearch.Region = String.Empty;
            paramSearch.PostalCode = String.Empty;
            paramSearch.CellPhone = String.Empty;
            paramSearch.OfficePhone = String.Empty;
            paramSearch.Title = String.Empty;
            paramSearch.PageNumber = 1;
            paramSearch.PageSize = 10;
            paramSearch.SortColumn = "UserProfileID";
            paramSearch.SortType = "asc";
            List<IUserProfile_biz> retVal = bs.UserProfileController_Search(paramSearch, true, true);
            if (retVal.Count > 0)
            {
                return retVal.FirstOrDefault();
            }
            else
            {
                return null;
            }
        }

        private IApplication_biz CreateNewApplication(string appName)
        {
            IApplication_biz param = new Application_biz();
            param.Action = "Add";
            param.ApplicationName = appName;
            param.CreatedBy = "System";
            param.CreatedDt = DateTime.Now;
            param.ModifiedBy = "System";
            param.ModifiedDt = DateTime.Now;
            IDictionary<string,int> r = bs.ApplicationController_Set(param);
            var ret = r.ToList().Select(s => new { Key = s.Key, Value = s.Value });
            Int32 retVal = ret.Where(z => z.Key == "Return_Value").Select(m => m.Value).FirstOrDefault();
            if (retVal <= 0)
            {
                return null;

            }
            else
            {
                IApplication_biz retVal2 = GetApplicationByName(appName);
                return retVal2;
            }
        }

        private IApplication_biz GetApplicationByName(string appName)
        {
            IApplicationSearch_biz searchParam = new ApplicationSearch_biz();
            searchParam.Action = "Search";
            searchParam.ApplicationName = appName;
            searchParam.PageNumber = 1;
            searchParam.PageSize = 10;
            searchParam.SortColumn = "ApplicationID";
            searchParam.SortType = "asc";
            List<IApplication_biz> retVal = bs.ApplicationController_Search(searchParam, false, false);
            if (retVal.Count == 0)
            {
                return null;
            }
            else
            {
                return retVal.FirstOrDefault();
            }
        }

        private IPasswordQuestion_biz GetPasswordQuestionByDesc(string _passwordQuestion)
        {
            IPasswordQuestionSearch_biz searchParam = new PasswordQuestionSearch_biz();
            searchParam.Action = "Search";
            searchParam.PasswordQuestionDesc = _passwordQuestion;
            searchParam.PageNumber = 1;
            searchParam.PageSize = 10;
            searchParam.SortColumn = "ApplicationID";
            searchParam.SortType = "asc";
            List<IPasswordQuestion_biz> retList = bs.PasswordQuestionController_Search(searchParam, false, false);
            if (retList == null || retList.Count == 0)
            {
                throw new ApplicationException("Password Question not found in the database");
            }
            return retList.FirstOrDefault();
        }

        private MembershipUser CreateMembershipUser(IUserProfile_biz _userObject)
        {
            MembershipUser retVal = new MembershipUser(this.ApplicationName, _userObject.UserName,
                _userObject.UserId, _userObject.Membership_List.FirstOrDefault().EmailAccount,
                _userObject.Membership_List.FirstOrDefault().PasswordQuestionID.ToString(), "", _userObject.IsActive, _userObject.IsActive, _userObject.CreatedDt,
                _userObject.Membership_List.FirstOrDefault().LastLoginDate, _userObject.Membership_List.FirstOrDefault().ModifiedDt,
                _userObject.Membership_List.FirstOrDefault().PasswordChangedDate, _userObject.Membership_List.FirstOrDefault().LastLockoutDate);

            return retVal;
        }

        private KeyValuePair<string, object> GetKVPByName(IDictionary<string, object> dictParam, string SearchKey)
        {
            foreach (KeyValuePair<string, object> _kvp in dictParam)
            {
                if (_kvp.Key.ToLower().Contains(SearchKey.ToLower()))
                {

                    return _kvp;



                }
            }
            return new KeyValuePair<string, object>("Empty", 0);
        }

        
    }
}
